package com.umeox.watch.moto.chat.widget;


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.common.utils.DeviceManager;
import com.umeox.moto.watch.themes.widget.ImageView;
import com.umeox.watch.moto.chat.R;
import com.umeox.watch.moto.chat.utils.Recorder;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class ChatRecorderDialog extends Dialog implements Recorder.OnRecorderListener {

    private Context mContext;
    private GestureDetector mGestureDetector;
    public static final long MAX_DURATION = TimeUnit.SECONDS.toMillis(60);
    private int startY = 0;
    private Recorder mRecorder;
    private TextView mTimerTv, mCancelTv;
    private ImageView mRecordIv, mAnimIv;
    private PowerManager.WakeLock wakeLock;
    private boolean mOriginalRaiseUpOn;

    private AnimationDrawable recordingAnim;

    public ChatRecorderDialog(@NonNull Context context) {
        super(context);

        mContext = context;
        mOriginalRaiseUpOn = DeviceManager.getInstance().isRaiseUpOn();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_recording);
        wakeUpAndUnlock();
        mTimerTv = findViewById(R.id.tv_timer);
        mRecordIv = findViewById(R.id.iv_record);
        mCancelTv = findViewById(R.id.tvRecordTip);
        mAnimIv = findViewById(R.id.ivAnim);
        final String voiceTip = mContext.getString(R.string.voice_tip);
        mTimerTv.setText(voiceTip);

        recordingAnim = (AnimationDrawable) mAnimIv.getDrawable();
        mGestureDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public void onLongPress(MotionEvent e) {
                updateUI();
            }
        });

        mRecordIv.setOnTouchListener(onTouchListener);

        mRecorder = Recorder.getInstance();
        mRecorder.seRecorderListener(this);

        //防止录音是按返回键造成bug
        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                    Logger.e("KEYCODE_BACK ACTION_UP");
                    boolean running = mRecorder.isRunning();
                    if (running)
                        mRecordIv.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mRecorder.stop();
                            }
                        }, 500);
                }
                return false;
            }
        });

    }


    private void updateUI() {
        mRecorder.start((int) MAX_DURATION);
        mAnimIv.setVisibility(View.VISIBLE);
        recordingAnim.start();
        mCancelTv.setVisibility(View.VISIBLE);
        if (mOriginalRaiseUpOn) {  //翻腕功能本身是开启的
            DeviceManager.getInstance().setRaiseUpValue(false);
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        releaseLock();
        if (mOriginalRaiseUpOn) {
            DeviceManager.getInstance().setRaiseUpValue(true);
        }
    }

    final View.OnTouchListener onTouchListener = new View.OnTouchListener() {

        private int startY = 0;

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (mRecorder == null) {
                return false;
            }
            mGestureDetector.onTouchEvent(event);
            int action = event.getAction();
            Logger.e("onTouch: " + action);
            final boolean running = mRecorder.isRunning();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    startY = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int currentY = (int) event.getRawY();
                    int disY = currentY - startY;
                    if (disY < -40 && mRecorder.isRunning()) {
                        mRecorder.cancel();
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    if (running)
                        mRecordIv.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mRecorder.stop();
                            }
                        }, 500);

                    break;
            }
            return false;
        }
    };

    @SuppressLint("InvalidWakeLockTag")
    private void wakeUpAndUnlock() {
        if (wakeLock == null) {
            PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
                    | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "Chat Recording");
        }

        wakeLock.acquire(MAX_DURATION);
    }

    private void releaseLock() {
        if (wakeLock != null) {

            try {
                wakeLock.release();
            } catch (Exception e) {
                Logger.e("Releasing wakelock failed:" + e);
            }
        } else {
            Logger.d("Wakelock reference is null");
        }
    }


    @Override
    public void onComplete(String filePath, long startMillis, long duration) {
        Logger.e("Chat", "duration=" + duration);
        if (recordingAnim != null && recordingAnim.isRunning()) {
            recordingAnim.stop();
        }
        if (mListener != null) {
            mListener.onVoice(filePath, duration);
        }

        dismiss();
    }

    @Override
    public void onUpdate(long duration) {
        mTimerTv.setText(String.format(Locale.getDefault(), "%d", TimeUnit.MILLISECONDS.toSeconds(MAX_DURATION - duration)) + "''");
    }

    @Override
    public void onError(Exception e) {
        if (recordingAnim != null && recordingAnim.isRunning()) {
            recordingAnim.stop();
        }
    }


    private OnDialogActionListener mListener;

    public void setListener(OnDialogActionListener listener) {
        mListener = listener;
    }

    public interface OnDialogActionListener {
        void onVoice(String filePath, long duration);

    }
}
